package com.xlz.statistics;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.xlz.domain.StatisticSelect;
import com.xlz.manager.DefaultDstManager;

/**
 * 加载统计缓存工具类.
 * @author 张蕾蕾
 * @date 2018 03 24
 */
public class SelectStatisticCache {

	private DefaultDstManager scheduleManager;

	private int size = 5000;
	private volatile List<StatisticSelect> cache = new ArrayList<StatisticSelect>(size);
	// 定义锁对象
	private Lock lock = new ReentrantLock();

	public void doStatistic(String appNo, Long taskId, String registerWorker, long loadDataTime, long loadDataTotal,
			int loadDataFlag, String errorContent) {
		lock.lock();
		try {
			StatisticSelect statistics = new StatisticSelect(appNo, taskId, registerWorker, loadDataTime,
					loadDataTotal, loadDataFlag, errorContent);
			int count = 0;
			while (size <= cache.size()) {
				cache.remove(0);
				count++;
				if (count >= size) {
					break;
				}
			}
			cache.add(statistics);
		} finally {
			lock.unlock();
		}
	}

	public List<StatisticSelect> cleanAndGet() {
		List<StatisticSelect> result = new ArrayList<StatisticSelect>();
		lock.lock();
		try {
			result.addAll(cache);
			cache.clear();
		} finally {
			lock.unlock();
		}
		return result;
	}

	public void flushToDb() {
		List<StatisticSelect> selectList = this.cleanAndGet();
		if (selectList != null && !selectList.isEmpty()) {
			scheduleManager.getStatisticSelectService().insertBatch(scheduleManager.getContext().getInstanceId(), selectList);
		}
	}

	public void setScheduleManager(DefaultDstManager scheduleManager) {
		this.scheduleManager = scheduleManager;
	}
}